﻿using psafth.AMB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.ComponentModel;
using System.Speech.Synthesis;

namespace psafth.RCTiming.Main.Views
{
    /// <summary>
    /// Interaction logic for AMBStatus.xaml
    /// </summary>
    public partial class AMBStatus : Window, INotifyPropertyChanged
    {
        private AMBCommunicator _decoderListener;
        private DispatcherTimer _timer;

        private bool isDecoderSpanSet = false;
        private bool isDecoderNoiseSet = false;

        [field: NonSerialized]
        public event PropertyChangedEventHandler PropertyChanged;

        public string ConsoleText
        {
            get;
            set;
        }

        public double InputVoltage
        {
            get;
            set;
        }

        public int Noise
        {
            get;
            set;
        }

        public double Temperature
        {
            get;
            set;
        }

        public TimeSpan DecoderTimeSpan
        {
            get;
            set;
        }

        public string ComputerTime
        {
            get
            {
                return DateTime.Now.ToString("HH:mm:ss");
            }
        }

        public string DecoderTime
        {
            get
            {
                return DateTime.Now.Add(DecoderTimeSpan).ToString("HH:mm:ss");
            }
        }

        public string DecoderAddress
        {
            get
            {
                return Properties.Settings.Default.DecoderIPAddress;
            }
        }


        public AMBStatus()
        {
            InitializeComponent();

            ConsoleText = string.Empty;

            _timer = new DispatcherTimer();
            _timer.Tick += _timer_Tick;
            _timer.Interval.Add(new TimeSpan(0, 0, 0, 0, 500));

            _decoderListener = new AMBCommunicator(Properties.Settings.Default.DecoderIPAddress, Properties.Settings.Default.DecoderTcpPort);
            _decoderListener.ProgressChanged += _decoderListener_ProgressChanged;
            _decoderListener.RunWorkerCompleted += _decoderListener_RunWorkerCompleted;
            _decoderListener.WorkerReportsProgress = true;
            _decoderListener.WorkerSupportsCancellation = true;

            _decoderListener.RunWorkerAsync();
        }

        void _timer_Tick(object sender, EventArgs e)
        {
            OnPropertyChanged("ComputerTime");
            OnPropertyChanged("DecoderTime");
        }

        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }

        void _decoderListener_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            ConsoleText += "Decoder frånkopplad.. " + Environment.NewLine;
            OnPropertyChanged("ConsoleText");
        }

        void _decoderListener_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            _timer.Start();

            TransferObject t = e.UserState as TransferObject;

            switch (t.MessageType)
            {
                case AMBMessageType.STATUS:
                    AMB.Status status = new AMB.Status(t.Data);
                    this.Noise = status.Noise;
                    this.InputVoltage = status.InputVoltage;
                    this.Temperature = status.Temperature;

                    ConsoleText += "Heartbeat from decoder.. " + Environment.NewLine;

                    OnPropertyChanged("Noise");
                    OnPropertyChanged("InputVoltage");
                    OnPropertyChanged("Temperature");
                    OnPropertyChanged("ConsoleText");

                    break;

                case AMBMessageType.GET_TIME:
                    AMB.GetTime time = new AMB.GetTime(t.Data);
                    this.DecoderTimeSpan = (DateTime.Now - time.RTCTime);
                    isDecoderSpanSet = true;
                    break;

                case AMBMessageType.PASSING:
                    AMB.Passing passing = new AMB.Passing(t.Data);

                    ConsoleText += string.Format("Passing by {0}" + Environment.NewLine, passing.TransponderId);

                    OnPropertyChanged("ConsoleText");
                    break;
            }

            svConsole.ScrollToBottom();

            if (!isDecoderSpanSet)
                _decoderListener.SendStream(AMBCommand.GetTime());
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            _decoderListener.Disconnect();

            _decoderListener.CancelAsync();


            //while (_decoderListener.CancellationPending)
            //{
            //    // Wait until the thread has shut down
            //}

            base.OnClosing(e);
        }
    }
}
